<?php


namespace app\api\common\member;

class Finance
{
	public static function set($user, $field, $number, $type, $remarks, $source, $extra_data = "")
	{
		if (!is_array($user)) {
			$user = \think\Db::name("app_member_user")->where(["id" => $user])->find();
		}
		if (empty($user)) {
			throw new \Exception("Finance.set->用户不存在" . $user);
		}
		$data = ["appid" => $user["appid"], "uid" => $user["id"], "field" => $field, "number" => $number, "type" => $type, "remarks" => $remarks, "after" => $type ? $user[$field] - $number : $user[$field] + $number, "ago" => $user[$field], "time" => time(), "source" => $source, "extra_data" => $extra_data];
		$up = \think\Db::name("app_member_user")->where(["id" => $user["id"]]);
		if ($field == "viptime") {
			$viptime = $number;
			$data["after"] = $viptime;
			if ($user["viptime"] <= $viptime) {
				$data["number"] = $viptime - $user["viptime"];
				$data["type"] = 0;
			} else {
				$data["number"] = $user["viptime"] - $viptime;
				$data["type"] = 1;
			}
			$is_forever_vip = $user["is_forever_vip"];
			if (\app\common\model\DefaultConfig::PerpetualTimeValue <= $viptime || \app\common\model\DefaultConfig::PerpetualTimeValue <= $number) {
				$is_forever_vip = 1;
				$viptime = \app\common\model\DefaultConfig::PerpetualTimeValue;
				$data["number"] = \app\common\model\DefaultConfig::PerpetualTimeValue;
			}
			\think\Db::name("app_member_user")->where("id", $user["id"])->update(["viptime" => $viptime, "is_forever_vip" => $is_forever_vip]);
		} else {
			if ($type == 0) {
				if ($field == "growth") {
					\think\Db::name("app_member_user")->where("id", $user["id"])->update(["growth_amass" => $user["growth_amass"] + $number]);
				}
				$up->setInc($field, $number);
			} else {
				$up->setDec($field, $number);
			}
		}
		return \think\Db::name("app_member_user_finance_log")->insertGetId($data);
	}
}